package tianrun.ziguan.api.forecast.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

/**
 * @author 18792
 */
public final class ResponseUtil {

    private final static Logger log = LoggerFactory.getLogger(ResponseUtil.class);

    private static ReturnMessage build(String msg,String code,String result) {
        ReturnMessage message = new ReturnMessage();
        message.setMessage(msg);
        message.setStatusCode(code);
        message.setResult(result);
        return message;
    }

    private static <T extends ReturnMessage> T build(T t,String msg,String code,String result) {
        t.setMessage(msg);
        t.setStatusCode(code);
        t.setResult(result);
        return t;
    }
    /****success******/

    private static ReturnMessage buildSuccess(String msg, String res) {
        return build(msg,FinalStrConfig.STR_RESPONSE_SUCCESS,res);
    }
    private static ReturnMessage buildSuccess(String msg) {
        return build(msg,FinalStrConfig.STR_RESPONSE_SUCCESS,FinalStrConfig.STR_OK);
    }

    public static <T> ResponseEntity<T> success(T t){
        return new ResponseEntity<>(t,HttpStatus.OK);
    }

    public static ResponseEntity<ReturnMessage> success(String message){
        return new ResponseEntity<>(buildSuccess(message),HttpStatus.OK);
    }

    public static ResponseEntity<ReturnMessage> success(String message,Object result){
        return new ResponseEntity<>(buildSuccess(message,result.toString()),HttpStatus.OK);
    }
    /*****error****/
    public static <T> ResponseEntity<T> error(T t) {
        return new ResponseEntity<>(t,HttpStatus.OK);
    }

    public static <T extends ReturnMessage> ResponseEntity<T> error (Class<T> ret, String message){
        try {
            T res = ret.newInstance();
            return success(build(res, message, FinalStrConfig.STR_RESPONSE_ERROR, FinalStrConfig.STR_ERROR));
        } catch (InstantiationException e) {
            log.error("ResponseUtil.error()-InstantiationException:",e);
        } catch (IllegalAccessException e) {
            log.error("ResponseUtil.error()-IllegalAccessException:",e);
        }
        return null;
    }
    public static ResponseEntity<ReturnMessage> error(String message){
        return new ResponseEntity<>(buildError(message),HttpStatus.OK);
    }

    public static ResponseEntity<ReturnMessage> error(String message,Object result){
        return new ResponseEntity<>(buildError(message,result.toString()),HttpStatus.OK);
    }

    private static ReturnMessage buildError(String msg, String res) {
        return build(msg,FinalStrConfig.STR_RESPONSE_ERROR,res);
    }


    private static ReturnMessage buildError(String msg) {
        return build(msg,FinalStrConfig.STR_RESPONSE_ERROR,FinalStrConfig.STR_ERROR);
    }

    
    
}
